<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>奖状制作模版</title>
  <script src="../css/tailwind3.4.17.css"></script>
  <link href="../css/all.min.css" rel="stylesheet">
  <link href="../css/my-font.css" rel="stylesheet">
  <script src="../js/html2canvas.min.js"></script>
  
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#D4AF37', // 金色
            secondary: '#8B0000', // 深红色
            accent: '#FFD700', // 亮金色
            neutral: '#F5F5DC', // 米黄色
            dark: '#333333', // 深灰色
          },
          fontFamily: {
            serif: ['Georgia', 'Cambria', 'Times New Roman', 'Times', 'serif'],
            sans: ['Helvetica', 'Arial', 'sans-serif'],
            'pen': ['MyFont-pen', 'cursive'],
            'xingshu': ['MyFont-GB2316', 'cursive'],
            'caoshu': ['MyFont-GB2313', 'cursive'],
            'shuxie': ['MyFont-GB2312', 'cursive'],
            'jifeng': ['fangyuan14', 'cursive'],
            'handwriting': ['MyFont-Regular', 'cursive'],
          },
          boxShadow: {
            'elegant': '0 4px 20px rgba(0, 0, 0, 0.15)',
            'gold': '0 0 15px rgba(212, 175, 55, 0.5)',
          }
        }
      }
    }
  </script>
  
  <style type="text/tailwindcss">
    @layer utilities {
      .text-shadow {
        text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
      }
      .text-shadow-gold {
        text-shadow: 0 0 5px rgba(212, 175, 55, 0.7);
      }
      .border-gold {
        border-image: linear-gradient(to right, #D4AF37, #FFD700, #D4AF37) 1;
      }
      .bg-texture {
        background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="%23F5F5DC" opacity="0.5"/><path d="M0 0L100 100M100 0L0 100" stroke="%23D4AF37" stroke-width="0.5" opacity="0.2"/></svg>');
        background-repeat: repeat;
      }
    }
    
    .certificate-container {
      position: relative;
      width: 100%;
      max-width: 600px;
      height: 450px;
      margin: 0 auto;
    }
    
    .certificate-bg {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-size: cover;
      background-position: center;
      z-index: 1;
    }
    
    .certificate-content {
      position: relative;
      z-index: 2;
      width: 100%;
      height: 100%;
    }
    
    .editable-text {
      position: absolute;
      cursor: pointer;
      transition: all 0.2s ease;
    }
    
    .editable-text:hover {
      outline: 2px dashed #D4AF37;
    }
    
    .template-item {
      transition: all 0.3s ease;
      cursor: pointer;
    }
    
    .template-item:hover {
      transform: translateY(-5px);
    }
    
    .template-item.active {
      border: 2px solid #D4AF37;
      box-shadow: 0 0 15px rgba(212, 175, 55, 0.7);
    }
    
    .font-option {
      transition: all 0.2s ease;
    }
    
    .font-option:hover {
      transform: scale(1.1);
    }
    
    .color-option {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      cursor: pointer;
      transition: all 0.2s ease;
    }
    
    .color-option:hover {
      transform: scale(1.2);
    }
    
    .color-option.active {
      border: 2px solid #333;
    }
    
    ::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }
    
    ::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb {
      background: #D4AF37;
      border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb:hover {
      background: #B8860B;
    }
  </style>
</head>
<body class="bg-gray-100 min-h-screen font-sans">
  <!-- 顶部导航栏 -->
  <header class="bg-white shadow-md">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
      <div class="flex items-center">
        <i class="fa fa-certificate text-primary text-2xl mr-2"></i>
        <h1 class="text-xl font-bold text-dark">奖状制作模版</h1>
      </div>
      <div class="flex items-center">
        <button id="saveBtn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-opacity-90 transition-colors flex items-center">
          <i class="fa fa-download mr-2"></i> 导出奖状
        </button>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="container mx-auto px-4 py-6">
    <div class="flex flex-col lg:flex-row gap-6">
      <!-- 左侧模板选择区 -->
      <div class="lg:w-1/5 bg-white rounded-lg shadow-elegant p-4">
        <h2 class="text-lg font-bold mb-4 text-dark border-b pb-2">选择模板</h2>
        <div class="grid grid-cols-1 gap-4" id="templateGallery">
          <!-- 模板将通过JavaScript动态加载 -->
        </div>
      </div>
      
      <!-- 中间编辑区 -->
      <div class="lg:w-3/5 bg-white rounded-lg shadow-elegant p-4">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-lg font-bold text-dark">奖状预览</h2>
          <div class="flex space-x-2">
            <button id="undoBtn" class="p-2 text-gray-600 hover:text-primary transition-colors" title="撤销">
              <i class="fa fa-undo"></i>
            </button>
            <button id="redoBtn" class="p-2 text-gray-600 hover:text-primary transition-colors" title="重做">
              <i class="fa fa-repeat"></i>
            </button>
          </div>
        </div>
        
        <!-- 奖状预览容器 -->
        <div class="border border-gray-200 rounded-lg p-4 bg-texture">
          <div id="certificateContainer" class="certificate-container bg-white shadow-lg">
            <div id="certificateBg" class="certificate-bg"></div>
            <div id="certificateContent" class="certificate-content flex flex-col items-center justify-center text-center p-8">
              <!-- 奖状内容将通过JavaScript动态加载 -->
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧工具栏 -->
      <div class="lg:w-1/5 bg-white rounded-lg shadow-elegant p-4">
        <h2 class="text-lg font-bold mb-4 text-dark border-b pb-2">自定义工具</h2>
        
        <!-- 文本编辑工具 -->
        <div class="mb-6">
          <h3 class="font-semibold text-gray-700 mb-3 flex items-center">
            <i class="fa fa-font mr-2 text-primary"></i> 文本编辑
          </h3>
          <div id="textTools" class="space-y-3">
            <!-- 文本编辑工具将通过JavaScript动态加载 -->
          </div>
        </div>
        
        <!-- 样式工具 -->
        <div class="mb-6">
          <h3 class="font-semibold text-gray-700 mb-3 flex items-center">
            <i class="fa fa-paint-brush mr-2 text-primary"></i> 样式设置
          </h3>
          
          <!-- 字体选择 -->
          <div class="mb-4">
            <label class="block text-sm text-gray-600 mb-2">字体</label>
            <div class="grid grid-cols-2 gap-2" id="fontOptions">
              <div class="font-option text-center p-2 border rounded cursor-pointer hover:border-primary" data-font="serif">
                <span class="font-serif">宋体</span>
              </div>
              <div class="font-option text-center p-2 border rounded cursor-pointer hover:border-primary" data-font="sans">
                <span class="font-sans">黑体</span>
              </div>
              <div class="font-option text-center p-2 border rounded cursor-pointer hover:border-primary" data-font="pen">
                <span class="font-pen">手写体</span>
              </div>
              <div class="font-option text-center p-2 border rounded cursor-pointer hover:border-primary" data-font="xingshu">
                <span class="font-xingshu">行书</span>
              </div>
              <div class="font-option text-center p-2 border rounded cursor-pointer hover:border-primary" data-font="caoshu">
                <span class="font-caoshu">草书</span>
              </div>
              <div class="font-option text-center p-2 border rounded cursor-pointer hover:border-primary" data-font="shuxie">
                <span class="font-shuxie">书写体</span>
              </div>
              <div class="font-option text-center p-2 border rounded cursor-pointer hover:border-primary" data-font="jifeng">
                <span class="font-jifeng">疾风草书</span>
              </div>
              <div class="font-option text-center p-2 border rounded cursor-pointer hover:border-primary" data-font="handwriting">
                <span class="font-handwriting">钢笔字</span>
              </div>
            </div>
          </div>
          
          <!-- 颜色选择 -->
          <div class="mb-4">
            <label class="block text-sm text-gray-600 mb-2">颜色</label>
            <div class="grid grid-cols-5 gap-2" id="colorOptions">
              <div class="color-option bg-black" data-color="#000000"></div>
              <div class="color-option bg-red-800" data-color="#8B0000"></div>
              <div class="color-option bg-primary active" data-color="#D4AF37"></div>
              <div class="color-option bg-blue-800" data-color="#00008B"></div>
              <div class="color-option bg-green-800" data-color="#006400"></div>
            </div>
          </div>
          
          <!-- 字体大小 -->
          <div>
            <label class="block text-sm text-gray-600 mb-2">字体大小</label>
            <input type="range" id="fontSizeSlider" min="12" max="72" value="24" class="w-full accent-primary">
            <div class="flex justify-between text-xs text-gray-500 mt-1">
              <span>小</span>
              <span id="fontSizeValue">24px</span>
              <span>大</span>
            </div>
          </div>
        </div>
        
        
      </div>
    </div>
  </main>

  

  <!-- 导出模态框 -->
  <div id="exportModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
      <div class="p-6">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-bold text-dark">导出奖状</h2>
          <button id="closeExportBtn" class="text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        <div class="space-y-4">
          <div>
            <label class="block text-sm text-gray-600 mb-2">文件名</label>
            <input type="text" id="exportFilename" value="荣誉证书" class="w-full border rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary">
          </div>
          <div>
            <label class="block text-sm text-gray-600 mb-2">文件格式</label>
            <div class="grid grid-cols-2 gap-2">
              <div class="format-option border rounded p-2 text-center cursor-pointer hover:border-primary active" data-format="png">
                <i class="fa fa-file-image-o mr-1"></i> PNG
              </div>
              <div class="format-option border rounded p-2 text-center cursor-pointer hover:border-primary" data-format="jpg">
                <i class="fa fa-file-image-o mr-1"></i> JPG
              </div>
            </div>
          </div>
          <div class="pt-4 flex justify-end">
            <button id="confirmExportBtn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-opacity-90 transition-colors">
              确认导出
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 通知模态框 -->
  <div id="notificationModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
      <div class="p-6">
        <div class="flex justify-between items-center mb-4">
          <h2 id="notificationTitle" class="text-xl font-bold text-dark">通知</h2>
          <button id="closeNotificationBtn" class="text-gray-500 hover:text-gray-700">
            <i class="fa fa-times text-xl"></i>
          </button>
        </div>
        <div class="space-y-4">
          <p id="notificationMessage" class="text-gray-700"></p>
          <div class="pt-4 flex justify-end">
            <button id="confirmNotificationBtn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-opacity-90 transition-colors">
              确定
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
    // 奖状模板数据
    const templates = [
      {
        id: 1,
        name: "经典金色",
        image: "",
        textFields: [
          { id: "title", text: "荣誉证书", top: "28%", left: "50%", fontSize: "36px", fontFamily: "serif", color: "#8B0000", fontWeight: "bold" },
          { id: "subtitle", text: "Certificate of Honor", top: "18%", left: "50%", fontSize: "18px", fontFamily: "pen", color: "#D4AF37" },
          { id: "recipient", text: "张三", top: "40%", left: "50%", fontSize: "28px", fontFamily: "serif", color: "#000000", fontWeight: "bold" },
          { id: "description", text: "在2025年度工作中表现突出，授予优秀员工称号", top: "55%", left: "50%", fontSize: "20px", fontFamily: "serif", color: "#333333" },
          { id: "issuer", text: "XX公司", top: "70%", left: "50%", fontSize: "22px", fontFamily: "serif", color: "#000000" },
          { id: "date", text: "2025年7月21日", top: "75%", left: "50%", fontSize: "18px", fontFamily: "pen", color: "#666666" }
        ]
      },
      {
        id: 2,
        name: "学生竞赛",
        image: "",
        textFields: [
          { id: "title", text: "荣誉证书", top: "28%", left: "50%", fontSize: "38px", fontFamily: "serif", color: "#8B0000", fontWeight: "bold" },
          { id: "recipient", text: "王五", top: "40%", left: "50%", fontSize: "28px", fontFamily: "serif", color: "#000000", fontWeight: "bold" },
          { id: "description", text: "在2025年全国大学生创新设计大赛中荣获一等奖", top: "52%", left: "50%", fontSize: "22px", fontFamily: "serif", color: "#333333" },
          { id: "description2", text: "特发此证，以资鼓励", top: "65%", left: "50%", fontSize: "20px", fontFamily: "xingshu", color: "#333333" },
          { id: "issuer", text: "XX大赛组委会", top: "75%", left: "50%", fontSize: "22px", fontFamily: "serif", color: "#000000" },
          { id: "date", text: "2025年7月21日", top: "82%", left: "50%", fontSize: "18px", fontFamily: "pen", color: "#666666" }
        ]
      }
    ];

    // 应用状态
    let appState = {
      currentTemplate: null,
      history: [],
      historyIndex: -1,
      selectedTextElement: null
    };

    // DOM元素
    const templateGallery = document.getElementById('templateGallery');
    const certificateBg = document.getElementById('certificateBg');
    const certificateContent = document.getElementById('certificateContent');
    const textTools = document.getElementById('textTools');
    const fontSizeSlider = document.getElementById('fontSizeSlider');
    const fontSizeValue = document.getElementById('fontSizeValue');
    
    const saveBtn = document.getElementById('saveBtn');
    const exportModal = document.getElementById('exportModal');
    const closeExportBtn = document.getElementById('closeExportBtn');
    const confirmExportBtn = document.getElementById('confirmExportBtn');
    const exportFilename = document.getElementById('exportFilename');
    const undoBtn = document.getElementById('undoBtn');
    const redoBtn = document.getElementById('redoBtn');
    
    const notificationModal = document.getElementById('notificationModal');
    const closeNotificationBtn = document.getElementById('closeNotificationBtn');
    const confirmNotificationBtn = document.getElementById('confirmNotificationBtn');
    const notificationTitle = document.getElementById('notificationTitle');
    const notificationMessage = document.getElementById('notificationMessage');

    // 初始化应用
    function init() {
      loadTemplates();
      bindEvents();
      if (templates.length > 0) {
        selectTemplate(templates[0].id);
      }
    }

    // 加载模板
    function loadTemplates() {
      templateGallery.innerHTML = '';
      
      templates.forEach(template => {
        const templateItem = document.createElement('div');
        templateItem.className = 'template-item rounded-lg overflow-hidden border';
        templateItem.dataset.id = template.id;
        
        templateItem.innerHTML = `
          <img src="${template.image}" alt="${template.name}" class="w-full h-40 object-cover">
          <div class="p-2 bg-white">
            <h3 class="font-medium text-center">${template.name}</h3>
          </div>
        `;
        
        templateGallery.appendChild(templateItem);
      });
    }

    // 绑定事件
    function bindEvents() {
      // 模板选择事件
      templateGallery.addEventListener('click', (e) => {
        const templateItem = e.target.closest('.template-item');
        if (templateItem) {
          const templateId = parseInt(templateItem.dataset.id);
          selectTemplate(templateId);
        }
      });
      
      // 字体选择事件 - 修复版
      document.querySelectorAll('#fontOptions .font-option').forEach(option => {
        option.addEventListener('click', () => {
          if (appState.selectedTextElement) {
            const font = option.dataset.font;
            
            // 移除所有字体类
            appState.selectedTextElement.classList.remove('font-serif', 'font-sans', 'font-pen', 'font-xingshu', 'font-caoshu', 'font-shuxie', 'font-jifeng', 'font-handwriting');
            
            // 添加选中的字体类
            appState.selectedTextElement.classList.add(`font-${font}`);
            
            // 更新UI
            document.querySelectorAll('#fontOptions .font-option').forEach(opt => {
              opt.classList.remove('border-primary');
            });
            option.classList.add('border-primary');
            
            // 保存状态
            saveState();
          } else {
            showNotification('请先点击奖状上的文字进行编辑', 'info');
          }
        });
      });
      
      // 颜色选择事件
      document.querySelectorAll('#colorOptions .color-option').forEach(option => {
        option.addEventListener('click', () => {
          if (appState.selectedTextElement) {
            const color = option.dataset.color;
            appState.selectedTextElement.style.color = color;
            
            document.querySelectorAll('#colorOptions .color-option').forEach(opt => {
              opt.classList.remove('active');
            });
            option.classList.add('active');
            
            saveState();
          } else {
            showNotification('请先点击奖状上的文字进行编辑', 'info');
          }
        });
      });
      
      // 字体大小滑块事件
      fontSizeSlider.addEventListener('input', () => {
        const size = fontSizeSlider.value;
        fontSizeValue.textContent = `${size}px`;
        
        if (appState.selectedTextElement) {
          appState.selectedTextElement.style.fontSize = `${size}px`;
          saveState();
        }
      });
      
      // 保存按钮事件
      saveBtn.addEventListener('click', () => {
        exportModal.classList.remove('hidden');
      });
      
      // 关闭导出模态框事件
      closeExportBtn.addEventListener('click', () => {
        exportModal.classList.add('hidden');
      });
      
      // 确认导出事件
      confirmExportBtn.addEventListener('click', () => {
        exportCertificate();
      });
      
      // 文件格式选择事件
      document.querySelectorAll('.format-option').forEach(option => {
        option.addEventListener('click', () => {
          document.querySelectorAll('.format-option').forEach(opt => {
            opt.classList.remove('active');
          });
          option.classList.add('active');
        });
      });
      
      // 撤销按钮事件
      undoBtn.addEventListener('click', () => {
        undo();
      });
      
      // 重做按钮事件
      redoBtn.addEventListener('click', () => {
        redo();
      });
      
      // 点击模态框外部关闭
      exportModal.addEventListener('click', (e) => {
        if (e.target === exportModal) {
          exportModal.classList.add('hidden');
        }
      });
      
      closeNotificationBtn.addEventListener('click', () => {
        notificationModal.classList.add('hidden');
      });
      
      confirmNotificationBtn.addEventListener('click', () => {
        notificationModal.classList.add('hidden');
      });
      
      notificationModal.addEventListener('click', (e) => {
        if (e.target === notificationModal) {
          notificationModal.classList.add('hidden');
        }
      });
      
      // 键盘快捷键
      document.addEventListener('keydown', (e) => {
        if (e.ctrlKey && e.key === 'z') {
          undo();
          e.preventDefault();
        }
        if (e.ctrlKey && e.key === 'y') {
          redo();
          e.preventDefault();
        }
        if (e.key === 'Escape') {
          exportModal.classList.add('hidden');
          notificationModal.classList.add('hidden');
        }
      });
    }

    // 选择模板
    function selectTemplate(templateId) {
      const template = templates.find(t => t.id === templateId);
      if (!template) return;
      
      appState.currentTemplate = template;
      
      // 更新模板选择UI
      document.querySelectorAll('.template-item').forEach(item => {
        if (parseInt(item.dataset.id) === templateId) {
          item.classList.add('active');
        } else {
          item.classList.remove('active');
        }
      });
      
      // 设置背景
      certificateBg.style.backgroundImage = `url(${template.image})`;
      certificateContent.innerHTML = '';
      
      // 创建文本元素
      template.textFields.forEach(field => {
        const textElement = document.createElement('div');
        textElement.className = 'editable-text transform -translate-x-1/2 -translate-y-1/2';
        textElement.dataset.id = field.id;
        textElement.textContent = field.text;
        textElement.style.top = field.top;
        textElement.style.left = field.left;
        textElement.style.fontSize = field.fontSize;
        textElement.style.color = field.color;
        
        // 添加字体类
        textElement.classList.add(`font-${field.fontFamily}`);
        
        if (field.fontWeight) {
          textElement.style.fontWeight = field.fontWeight;
        }
        
        if (field.textShadow) {
          textElement.style.textShadow = field.textShadow;
        }
        
        // 点击编辑事件
        textElement.addEventListener('click', () => {
          selectTextElement(textElement);
        });
        
        certificateContent.appendChild(textElement);
      });
      
      // 保存状态
      saveState();
      updateTextTools();
    }

    // 选择文本元素
    function selectTextElement(element) {
      if (appState.selectedTextElement) {
        appState.selectedTextElement.classList.remove('outline');
      }
      
      appState.selectedTextElement = element;
      element.classList.add('outline', 'outline-2', 'outline-primary');
      
      // 更新工具面板
      updateTextTools();
      
      // 更新字体大小滑块
      const fontSize = parseInt(element.style.fontSize);
      fontSizeSlider.value = fontSize;
      fontSizeValue.textContent = `${fontSize}px`;
      
      // 更新颜色选择
      const color = element.style.color;
      document.querySelectorAll('#colorOptions .color-option').forEach(option => {
        if (option.dataset.color === color) {
          option.classList.add('active');
        } else {
          option.classList.remove('active');
        }
      });
      
      // 更新字体选择
      let fontFamily = 'serif';
      if (element.classList.contains('font-sans')) fontFamily = 'sans';
      else if (element.classList.contains('font-pen')) fontFamily = 'pen';
      else if (element.classList.contains('font-xingshu')) fontFamily = 'xingshu';
      else if (element.classList.contains('font-caoshu')) fontFamily = 'caoshu';
      
      document.querySelectorAll('#fontOptions .font-option').forEach(option => {
        if (option.dataset.font === fontFamily) {
          option.classList.add('border-primary');
        } else {
          option.classList.remove('border-primary');
        }
      });
    }

    // 更新文本工具
    function updateTextTools() {
      if (appState.selectedTextElement) {
        const textId = appState.selectedTextElement.dataset.id;
        const text = appState.selectedTextElement.textContent;
        
        textTools.innerHTML = `
          <div class="mb-3">
            <label class="block text-sm text-gray-600 mb-2">当前编辑: ${getTextLabel(textId)}</label>
            <input type="text" value="${text}" class="w-full border rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary" id="textEditInput">
          </div>
          <div class="flex justify-between">
            <button id="boldBtn" class="px-3 py-1 border rounded hover:bg-gray-100 ${appState.selectedTextElement.style.fontWeight === 'bold' ? 'bg-gray-100' : ''}">
              <i class="fa fa-bold"></i>
            </button>
            <button id="italicBtn" class="px-3 py-1 border rounded hover:bg-gray-100 ${appState.selectedTextElement.style.fontStyle === 'italic' ? 'bg-gray-100' : ''}">
              <i class="fa fa-italic"></i>
            </button>
            <button id="underlineBtn" class="px-3 py-1 border rounded hover:bg-gray-100 ${appState.selectedTextElement.style.textDecoration === 'underline' ? 'bg-gray-100' : ''}">
              <i class="fa fa-underline"></i>
            </button>
            <button id="textShadowBtn" class="px-3 py-1 border rounded hover:bg-gray-100 ${appState.selectedTextElement.style.textShadow ? 'bg-gray-100' : ''}">
              <i class="fa fa-sun-o"></i>
            </button>
          </div>
        `;
        
        // 文本输入事件
        document.getElementById('textEditInput').addEventListener('input', (e) => {
          appState.selectedTextElement.textContent = e.target.value;
          saveState();
        });
        
        // 粗体按钮事件
        document.getElementById('boldBtn').addEventListener('click', () => {
          const isBold = appState.selectedTextElement.style.fontWeight === 'bold';
          appState.selectedTextElement.style.fontWeight = isBold ? 'normal' : 'bold';
          document.getElementById('boldBtn').classList.toggle('bg-gray-100');
          saveState();
        });
        
        // 斜体按钮事件
        document.getElementById('italicBtn').addEventListener('click', () => {
          const isItalic = appState.selectedTextElement.style.fontStyle === 'italic';
          appState.selectedTextElement.style.fontStyle = isItalic ? 'normal' : 'italic';
          document.getElementById('italicBtn').classList.toggle('bg-gray-100');
          saveState();
        });
        
        // 下划线按钮事件
        document.getElementById('underlineBtn').addEventListener('click', () => {
          const isUnderline = appState.selectedTextElement.style.textDecoration === 'underline';
          appState.selectedTextElement.style.textDecoration = isUnderline ? 'none' : 'underline';
          document.getElementById('underlineBtn').classList.toggle('bg-gray-100');
          saveState();
        });
        
        // 文字阴影按钮事件
        document.getElementById('textShadowBtn').addEventListener('click', () => {
          const hasShadow = appState.selectedTextElement.style.textShadow;
          appState.selectedTextElement.style.textShadow = hasShadow ? '' : '2px 2px 4px rgba(0, 0, 0, 0.3)';
          document.getElementById('textShadowBtn').classList.toggle('bg-gray-100');
          saveState();
        });
      } else {
        textTools.innerHTML = `
          <div class="text-center text-gray-500 py-4">
            <i class="fa fa-hand-pointer-o text-2xl mb-2"></i>
            <p>点击奖状上的文字进行编辑</p>
          </div>
        `;
      }
    }

    // 获取文本标签
    function getTextLabel(textId) {
      const labels = {
        'title': '标题',
        'subtitle': '副标题',
        'recipient': '获奖者',
        'description': '描述',
        'description2': '描述2',
        'issuer': '颁发机构',
        'date': '日期'
      };
      
      return labels[textId] || textId;
    }

    // 保存状态
    function saveState() {
      if (appState.historyIndex < appState.history.length - 1) {
        appState.history = appState.history.slice(0, appState.historyIndex + 1);
      }
      
      const currentState = {
        templateId: appState.currentTemplate.id,
        textFields: []
      };
      
      document.querySelectorAll('.editable-text').forEach(element => {
        let fontFamily = 'serif';
        if (element.classList.contains('font-sans')) fontFamily = 'sans';
        else if (element.classList.contains('font-pen')) fontFamily = 'pen';
        else if (element.classList.contains('font-xingshu')) fontFamily = 'xingshu';
        else if (element.classList.contains('font-caoshu')) fontFamily = 'caoshu';
        
        currentState.textFields.push({
          id: element.dataset.id,
          text: element.textContent,
          top: element.style.top,
          left: element.style.left,
          fontSize: element.style.fontSize,
          fontFamily: fontFamily,
          color: element.style.color,
          fontWeight: element.style.fontWeight,
          fontStyle: element.style.fontStyle,
          textDecoration: element.style.textDecoration,
          textShadow: element.style.textShadow
        });
      });
      
      appState.history.push(currentState);
      appState.historyIndex = appState.history.length - 1;
      
      updateUndoRedoButtons();
    }

    // 更新撤销重做按钮状态
    function updateUndoRedoButtons() {
      undoBtn.disabled = appState.historyIndex <= 0;
      redoBtn.disabled = appState.historyIndex >= appState.history.length - 1;
      
      if (undoBtn.disabled) {
        undoBtn.classList.add('text-gray-400');
        undoBtn.classList.remove('text-gray-600', 'hover:text-primary');
      } else {
        undoBtn.classList.remove('text-gray-400');
        undoBtn.classList.add('text-gray-600', 'hover:text-primary');
      }
      
      if (redoBtn.disabled) {
        redoBtn.classList.add('text-gray-400');
        redoBtn.classList.remove('text-gray-600', 'hover:text-primary');
      } else {
        redoBtn.classList.remove('text-gray-400');
        redoBtn.classList.add('text-gray-600', 'hover:text-primary');
      }
    }

    // 撤销操作
    function undo() {
      if (appState.historyIndex > 0) {
        appState.historyIndex--;
        restoreState(appState.history[appState.historyIndex]);
      }
    }

    // 重做操作
    function redo() {
      if (appState.historyIndex < appState.history.length - 1) {
        appState.historyIndex++;
        restoreState(appState.history[appState.historyIndex]);
      }
    }

    // 恢复状态
    function restoreState(state) {
      selectTemplate(state.templateId);
      
      state.textFields.forEach(field => {
        const element = document.querySelector(`.editable-text[data-id="${field.id}"]`);
        if (element) {
          element.textContent = field.text;
          element.style.top = field.top;
          element.style.left = field.left;
          element.style.fontSize = field.fontSize;
          element.style.color = field.color;
          element.style.fontWeight = field.fontWeight || 'normal';
          element.style.fontStyle = field.fontStyle || 'normal';
          element.style.textDecoration = field.textDecoration || 'none';
          element.style.textShadow = field.textShadow || '';
          
          // 移除所有字体类
          element.classList.remove('font-serif', 'font-sans', 'font-pen', 'font-xingshu', 'font-caoshu', 'font-shuxie', 'font-jifeng', 'font-handwriting');
          
          // 添加选中的字体类
          element.classList.add(`font-${field.fontFamily}`);
        }
      });
      
      appState.selectedTextElement = null;
      
      updateTextTools();
      updateUndoRedoButtons();
    }

    // 导出奖状
    function exportCertificate() {
      const filename = exportFilename.value || '荣誉证书';
      const format = document.querySelector('.format-option.active').dataset.format;
      
      html2canvas(document.getElementById('certificateContainer')).then(canvas => {
        const link = document.createElement('a');
        
        if (format === 'png') {
          link.href = canvas.toDataURL('image/png');
          link.download = `${filename}.png`;
        } else {
          link.href = canvas.toDataURL('image/jpeg', 0.95);
          link.download = `${filename}.jpg`;
        }
        
        link.click();
        exportModal.classList.add('hidden');
        showNotification('奖状导出成功！', 'success');
      });
    }

    // 显示通知
    function showNotification(message, type = 'info') {
      notificationMessage.textContent = message;
      
      if (type === 'success') {
        notificationTitle.textContent = '成功';
        notificationTitle.classList.remove('text-red-600');
        notificationTitle.classList.add('text-green-600');
      } else if (type === 'error') {
        notificationTitle.textContent = '错误';
        notificationTitle.classList.remove('text-green-600');
        notificationTitle.classList.add('text-red-600');
      } else {
        notificationTitle.textContent = '通知';
        notificationTitle.classList.remove('text-green-600', 'text-red-600');
      }
      
      notificationModal.classList.remove('hidden');
    }
    
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', init);
  </script>
</body>
</html>